package cc.linker.steplink.crm.commons;

import com.mongodb.util.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

@Deprecated
public class CallService {

    final private static String FORM_TYPE = "application/x-www-form-urlencoded";
    final private static String JSON_TYPE = "application/json";

    /**
     * post请求调用接口(form)
     *
     * @param url     地址
     * @param content 参数
     * @return
     */
    public static Object post(String url, String content) {
        return doPost(url, content, FORM_TYPE);
    }

    /**
     * post请求调用接口(json)
     *
     * @param url     地址
     * @param content 参数
     * @return
     */
    public static Object jsonPost(String url, String content) {
        return doPost(url, content, JSON_TYPE);
    }

    private static Object doPost(String url, String content, String type) {
        try {
            String charset = "UTF-8";
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            post.setHeader("Authorization", "bearer AT-9e4207df80df5b54a7e2e8ef6192d59f");
            post.setHeader("Content-Type", type + ";charset=UTF-8");
            StringEntity se = new StringEntity(content, charset);
            se.setContentEncoding(charset);
            se.setContentType(type);
            post.setEntity(se);
            CloseableHttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            String resData = EntityUtils.toString(entity);
            client.close();
            return JSON.parse(resData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * get请求调用接口
     *
     * @param url 地址
     * @return
     */
    public static Object get(String url) {
        try {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            get.setHeader("Authorization", "bearer AT-9e4207df80df5b54a7e2e8ef6192d59f");
            CloseableHttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            String resData = EntityUtils.toString(entity);
            client.close();
            return JSON.parse(resData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
